import React from 'react';
import {connect,} from 'react-redux';
import './Football.css';
import GameSchedule from "./GameSchedule/GameSchedule";
import GameResult from "./GameResult/GameResult";
import AllGame from "./AllGame/AllGame";
import LiveGame from "./LiveGame/LiveGame";
import GoalSpeaker from "../../game-room/components/Main/chat-room/GoalSpeaker/GoalSpeaker";
import MarkedGame from "./MarkedGame/MarkedGame";
import LocalStorageService from "../../../utils/LocalStorageService";
import {Tabs} from "antd-mobile";
import {formatDate, handleDateChange} from "../../../utils/dateService";
import {behaviorReq, getHotReq} from "../../../apis/goApis";
import allSrcActive from "../../../res/images/web/game/地球-白@2x.png"
import allSrcNative from "../../../res/images/web/game/地球-黑@2x.png"
import hotSrcActive from "../../../res/images/web/game/奖杯-白@2x.png"
import hotSrcNative from "../../../res/images/web/game/奖杯-黑@2x.png"
import HotGameButton from "./HotGameButton/HotGameButton";
import IconSwiper from "./IconSwiper/IconSwiper";

class Football extends React.Component {

    constructor(props) {
        
        super(props)

        this.tabs = [
            {title: '全部',},
            {title: '进行中',},
            {title: '赛程',},
            {title: '赛果',},
            {title: '关注',},
        ]
        this.state = {
            includeYesterdayMatch: false,
            hot: false,
            hots: [],
        }
    }

    componentDidMount() {
        // console.log(this.props)
        // this.setDownloadShow()

        // const today = this.props.today
        const tabPosition = this.props.tabPosition
        if (tabPosition[1] === 0 || tabPosition[1] === 1) {
            this.fetchGameList()
        }
        this.fetchMarkList()
        this.getHot()
    }

    getHot = () => {
        getHotReq()
            .then((res) => {
                const hots = res.data.ok.zq
                this.setState({
                    hots,
                })
            })
    }

    fetchToday = () => {
        const now = new Date()
        const today = formatDate(now)
        return this.props.doFetchGameListAll({
            date: today,
        })
    }

    fetchYesterday = (today) => {
        const yesterday = formatDate(handleDateChange(today, -1))
        this.props.doFetchGameListAll({
            date: yesterday,
            toast: false,
        }).then((success) => {
            if (success) {
                this.setState({
                    includeYesterdayMatch: true,
                })
            }
        })
    }


    fetchGameList = () => {
        const now = new Date()
        const today = formatDate(now)
        return this.fetchToday()
            .then(() => {
                const start = 0
                const end = 3
                const isBetween9and3 = this.checkIsNowBetween(now, start, end)
                if (isBetween9and3) {
                    this.fetchYesterday(today)
                }
                const {
                    matches,
                } = this.props.games[today]
                if (matches.length > 0) {
                    // console.log('有数据 开始轮询')
                    this.freshMatchList()
                }
            })
    }


    checkIsNowBetween = (now, start, end) => {
        const h = now.getHours()
        return h >= start && h <= end

    }

    setDownloadShow = () => {
        const downloadShow = this.context.downloadApp.show
        this.setState({
            downloadShow,
        })
    }


    // shouldComponentUpdate(nextProps, nextState, nextContext) {
    //     console.log('shouldComponentUpdate')
    //     console.log(this.props)
    //     console.log(nextProps)
    //     return this.props.downloadShow !== nextProps.downloadShow
    //
    // }

    componentWillUnmount() {
        // console.log('Football unmounted')
        this.clearFreshMatchList()
        // this.props.doGameTabPositionInit()
    }

    freshMatchList = () => {
        const freshInterval = 5000
        this.freshInterval = setInterval(() => {
            // console.log('刷新比赛列表')
            const now = formatDate(new Date())

            if (now !== this.props.today) {
                this.clearFreshMatchList()
                this.fetchGameList()
                    .then(() => {
                        this.updateToday(now)
                    })
            } else {
                this.props.doFetchGameListLive()
            }
        }, freshInterval)

    }

    updateToday = today => {
        this.props.updateToday({today,})
    }

    clearFreshMatchList = () => {
        this.freshInterval && clearInterval(this.freshInterval)
    }

    setInitTabPosition = () => {

    }

    setTabPosition = (e, i) => {

        const isLogin = LocalStorageService.get('userid')
        if (isLogin) {
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: e.title,
            })
        }
        setTimeout(() => {
            this.props.changeEventFilter({
                eventFilters: [],
            })
        }, 0)
        setTimeout(() => {
            this.props.changeGameTabPosition({
                position: i,
                depth: 1,
            })
        }, 0)

    }

    fetchMarkList = () => {
        const storage = LocalStorageService
        const isLogin = storage.get('isLogin')
        if (isLogin) {
            const list = this.props.game.markList
            if (list.length !== 0) {
                storage.markGameList(list,)
            }
            if (list.length === 0) {
                const uid = storage.get('userid')
                this.props.doFetchMarkList({
                    uid,
                })
            }
        }
    }

    setHot = (value) => {
        this.setState({
            hot: value,
        })
    }

    render() {

        const update = this.props.update
        const initialPage = this.props.tabPosition[1]
        const downloadShow = this.props.downloadShow

        const tabs = [
            {title: '全部',},
            {title: '进行中',},
            {title: '赛程',},
            {title: '赛果',},
            {title: '关注',},
        ]

        return (

            <div
                style={{
                    position: 'relative',
                    overflow: 'hidden',
                    height: downloadShow
                        ? document.documentElement.clientHeight - 50 - 60 - 43.5
                        : document.documentElement.clientHeight - 50 - 43.5
                }}
            >
                {/*<IconSwiper />*/}
                <HotGameButton
                    hot={this.state.hot}
                    setHot={this.setHot}
                />
                <Tabs
                    tabs={tabs}
                    tabBarBackgroundColor='#183041'
                    tabBarActiveTextColor='#FFFFFF'
                    tabBarUnderlineStyle={{border: '2px #36C8B9 solid'}}
                    tabBarInactiveTextColor='rgba(255, 255, 255, 0.4)'
                    tabBarTextStyle={{fontSize: '14px',}}
                    // prefixCls='game-page-tab'
                    onChange={(e, i) => this.setTabPosition(e, i)}
                    prerenderingSiblingsNumber={0}
                    animated={false}
                    initialPage={initialPage}
                    page={initialPage}
                    destroyInactiveTab={true}
                    swipeable={false}
                >

                    <AllGame
                        includeYesterdayMatch={this.state.includeYesterdayMatch}
                        hot={this.state.hot}
                        hots={this.state.hots}
                    />
                    <LiveGame
                        includeYesterdayMatch={this.state.includeYesterdayMatch}
                        hot={this.state.hot}
                        hots={this.state.hots}
                    />
                    <GameSchedule
                        hot={this.state.hot}
                        hots={this.state.hots}
                    />
                    <GameResult
                        hot={this.state.hot}
                        hots={this.state.hots}
                    />
                    <MarkedGame
                        hot={this.state.hot}
                        hots={this.state.hots}
                    />
                </Tabs>
                {/*<GameLayout*/}
                {/*    tabs={tabs}*/}
                {/*    initialPage={initialPage}*/}
                {/*    page={initialPage}*/}
                {/*    // onTabClick={(e, i) => this.setTabPosition(e, i)}*/}
                {/*    onTabChange={(e, i) => this.setTabPosition(e, i)}*/}
                {/*>*/}
                {/*    <AllGame />*/}
                {/*    <LiveGame />*/}
                {/*    <GameSchedule/>*/}
                {/*    <GameResult />*/}
                {/*    <MarkedGame />*/}
                {/*</GameLayout>*/}
                {update.length > 0 ? <GoalSpeaker dataArr={update}/> : null}
            </div>
        )
    }
}



const mapState = state => ({
    game: state.game,
    games: state.game.games,
    today: state.game.today,
    update: state.game.update,
    tabPosition: state.game.tabPosition,
    eventFilters: state.game.eventFilters,
})

const mapDispatch = dispatch => ({
    doFetchGameList: (payload) => dispatch.game.doFetchGameList(payload),
    doFetchGameListAll: (payload) => dispatch.game.doFetchGameListAll(payload),
    doFetchGameListLive: (payload) => dispatch.game.doFetchGameListLive(payload),
    doFetchOddsListAll: (payload) => dispatch.game.doFetchOddsListAll(payload),
    doFetchOddsEuroLive: (payload) => dispatch.game.doFetchOddsEuroLive(payload),
    changeGameTabPosition: (payload) => dispatch.game.changeGameTabPosition(payload),
    changeEventFilter: (payload) => dispatch.game.changeEventFilter(payload),
    doFetchMarkList: (payload) => dispatch.game.doFetchMarkList(payload),
    doGameTabPositionInit: () => dispatch.game.doGameTabPositionInit(),
    updateToday: (payload) => dispatch.game.updateToday(payload),
})

export default connect(mapState, mapDispatch)(Football)
